package com.jy.modules.cims.component.settle;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.sysUtils.FileUtils;
import com.jy.modules.cims.data.dto.AnnotationDto;

/**
 * @description  解析及生成带分割符文件
 * @author zhuwenbin
 *
 */
@Service("com.jy.modules.cims.component.settle.CCimsFileOperImpl")
public class CCimsFileOperImpl implements ICimsFileOper {
	
	 private static final Logger logger =  LoggerFactory.getLogger(CCimsFileOperImpl.class);

	@Override
	public List<String[]> analyRegexFile(String fileFullName, String regex,int column) {
		File analyFile = null;
		List<String[]> analyList = null;
		BufferedReader bufferedreader = null;
		InputStreamReader insReader = null;
		FileInputStream fileins = null;
		try {
			analyFile = new File(fileFullName);
			//判断文件是否存在
			if (analyFile.exists()) {
				fileins = new FileInputStream(analyFile);
				insReader = new InputStreamReader(fileins,CimsConstant.HYL_FILECHARSET);
				bufferedreader = new BufferedReader(insReader);
				String readerline = null;
				analyList = new ArrayList<String[]>();
				//读取并按照分割符解析
				while (bufferedreader.ready()) {
					readerline = bufferedreader.readLine();
					if (readerline == null || "".equals(readerline)) {
						continue;
					}
					String[] splitStr = readerline.split(regex,column);
					analyList.add(splitStr);
				}
			} else {
				logger.error( fileFullName + "文件不存在！");
			}
		} catch (Exception e) {
			logger.error("analyFile方法文件" + fileFullName + "解析异常", e);
		} finally {
			if (bufferedreader != null) {
				try {
					bufferedreader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (insReader != null) {
				try {
					insReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
			if(fileins != null){
				try {
					fileins.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return analyList;

	}
	
 

	@Override
	public boolean writeFile(String fileFullName, List<StringBuffer> listStr) {
		
		File file = null;
		FileOutputStream fileos = null;
		PrintWriter writer = null;
		boolean flag = false;
		try {
			file = new File(fileFullName);
			if(file.createNewFile()){
				fileos = new FileOutputStream(file);
				writer = new PrintWriter(fileos);
				for(StringBuffer strbuffer : listStr){
					strbuffer.append(System.getProperty(CimsConstant.LINE_SEPARATOR));
					writer.write(strbuffer.toString());
					writer.flush();
				}
				flag = true;
			}else{
				logger.error("writeFile方法生成文件"+fileFullName+"异常！");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(writer != null){
				writer.close();
			}
			if(fileos != null){
				try {
					fileos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return flag;
	}
	
	
	
	 /**
     * 将数组转化为DTO对象
     * @param clazz
     * @param str
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
	public Object stringConvertDTO(Class clazz,String[] str ) throws  Exception{
		
		Object obj = clazz.newInstance();
		Field[] fields  = obj.getClass().getDeclaredFields();
		for(Field field :  fields){
			boolean flag = field.isAccessible();
			field.setAccessible(true);
			//获取字段所对应数组中的索引
			AnnotationDto annotation =  field.getAnnotation(AnnotationDto.class);
			//从数组中取值置入对象
			field.set(obj, str[annotation.index()]);
			field.setAccessible(flag);  
		}
		return obj;
		
	}
	
	/**
	 * @description DTO对象转换为StringBuffer字段用regex分割
	 * @param obj
	 * @param regex
	 * @return
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	public StringBuffer DtoConvertString(Object obj,String regex) throws IllegalArgumentException, IllegalAccessException{
		StringBuffer stringBuffer = null;
		if(regex == null || "".equals(regex) || obj == null){
			logger.error("分隔符为空！ ");
			return stringBuffer;
		}
		
		stringBuffer = new StringBuffer();
		Field[] fields = obj.getClass().getDeclaredFields();
		for(Field field : fields){
			
			String value = (String) field.get(obj);
			if(value ==null){
				stringBuffer.append("");
			}else{
				stringBuffer.append(value);
				
			}
			
			stringBuffer.append(regex);
		}
		//删除最后一位分割符
		stringBuffer.replace(stringBuffer.lastIndexOf(regex), stringBuffer.length(), "");
		return stringBuffer;
		
	}
	

    
    
    
    /**
	 * @description 解析回盘文件
	 * @param fileFullName
	 *        文件全路径名称
	 * @param regex
	 *        分隔符
	 * @param limit
	 *        列数
	 * @param hzclass
	 *        第一行汇总明细类
	 * @param detailclass
	 *         明细类           
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
    public List<Object> analyHPFile(String fileFullName,String regex,int limit,Class hzclass,Class detailclass) throws Exception{
    	
    	//按分隔符解析文件生成数组列表
    	List<String[]> dataList =  FileUtils.analyRegexFile(fileFullName,regex,limit);
    	List<Object> objList = new ArrayList<Object>();
    	int i = 0;
    	Object hz = hzclass.newInstance();
    	Object detail = detailclass.newInstance();
    	for(i = 0;i<dataList.size(); i++){
    		if(i==0){
    			//第一行解析文件汇总
    			 hz = (Object) stringConvertDTO(hzclass, dataList.get(i));
    			 objList.add(hz);
    		}else{
    			 //解析文件内容
    			 detail = (Object) stringConvertDTO(detailclass, dataList.get(i));
    			 objList.add(detail);
    		}
    		
    	}
       return objList;
    	
    }
    


    
    
    /**
	 * @description 解析回盘文件文件
	 * @param fileFullName
	 *        文件全路径名称
	 * @param regex
	 *        分隔符
	 * @param limit
	 *        列数
	 * @param hzclass
	 *        第一行汇总明细类
	 * @param detailclass
	 *         明细类              
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
    public List<Object> analyHPFileByStream(InputStream in,String regex,int limit,Class hzclass,Class detailclass) throws Exception{
    	
    	//按分隔符解析文件生成数组列表
    	List<String[]> dataList =  FileUtils.analyRegexByStream(in,regex,limit);
       	int totalNum = dataList.size();
    	List<Object> objList = new ArrayList<Object>(totalNum);
    	int i = 0;
    	Object hz = hzclass.newInstance();
    	Object detail = detailclass.newInstance();
 
    	for(i = 0;i<totalNum; i++){
    		if(i==0){
    			//第一行解析文件汇总
    			 hz = (Object) stringConvertDTO(hzclass, dataList.get(i));
    			 objList.add(hz);
    		}else{
    			 //解析文件内容
    			 detail = (Object) stringConvertDTO(detailclass, dataList.get(i));
    			 objList.add(detail);
    		}
    		
    	}
       return objList;
    	
    }
    
    
    
    /**
     * @description 生成报盘文件
     * @param objList
     *        数据集
     * @param OutputStream
     *        输出流
     * @param regex
     *        分隔符号
     * @return
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public boolean createBPFile(List<Object> objList,OutputStream os,String regex) throws IllegalArgumentException, IllegalAccessException{
    	boolean flag = false;
    	List<StringBuffer> strList =  new ArrayList<StringBuffer>(objList.size());
    	for(Object obj : objList){
    		//将dto装化为字符串列表
    		StringBuffer strBuffer = DtoConvertString(obj, regex);
    		strList.add(strBuffer);
    	}
    	//将字符串列表写入文件
    	flag = FileUtils.writeFile(strList,os);
    	
    	return flag;
    }

}
